package com.weixing.mall.provider.controller.rpc;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weixing.mall.base.orm.MPage;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.dto.MemberAgentBindDto;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.model.domain.Member;
import com.weixing.mall.provider.service.IMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @Author wx
 * @Date 2019/12/4 15:34
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/member")
public class MemberRpcController extends BaseController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private AgentServiceRpc agentServiceRpc;
    @Autowired
    private OrderServiceRpc orderServiceRpc;

    @GetMapping("selectById")
    public Result<MemberRpcVo> selectByAgentSn(Long id) {
        return ResultUtil.success(memberService.selectByIdMemberRpcVo(id));
    }

    @PostMapping("saveOrUpdateMember")
    public Result saveByAgentId(@RequestBody MemberAgentBindDto bindDto) {
        memberService.saveOrUpdateMember(bindDto);
        return ResultUtil.success();
    }

    @GetMapping("changAgentStatus")
    public Result changAgentByAgentId(Long agentId) {
        memberService.changAgentStatus(agentId);
        return ResultUtil.success();
    }

    @GetMapping("loadUserByUsername")
    public Result<MemberAuthVo> loadUserByUsername(String mobile) {
        Member member = memberService.selectByMobile(mobile);
        MemberAuthVo authVo = null;
        if (null != member) {
            authVo = new MemberAuthVo();
            BeanUtils.copyProperties(member, authVo);
            long agentRoleBindId = member.getAgentRoleBindId();
            if (0 != agentRoleBindId) {
                Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(agentRoleBindId);
                loadMemberAuthVoData(authVo, agentRpcVoResult);
                if (agentRpcVoResult.isSuccess() && ObjectUtil.isNotEmpty(agentRpcVoResult.getData())) {
                    authVo.setKefuId(agentRpcVoResult.getData().getCustomerId());
                    authVo.setKefuName(agentRpcVoResult.getData().getCustomerName());
                }
            } else if (null != member.getAgentId()) {
                Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(member.getAgentId());
                if (agentRpcVoResult.isSuccess()) {
                    AgentRpcVo data = agentRpcVoResult.getData();
                    if (null != data) {
                        authVo.setAgentTreePath(data.getAgentTreePath());
                        authVo.setKefuId(data.getCustomerId());
                        authVo.setKefuName(data.getCustomerName());
                    }
                }

            }
        }
        return ResultUtil.success(authVo);
    }

    private MemberAuthVo loadMemberAuthVoData(MemberAuthVo authVo, Result<AgentRpcVo> agentRpcVoResult) {
        if (agentRpcVoResult.isSuccess() && ObjectUtil.isNotEmpty(agentRpcVoResult.getData())) {
            AgentRpcVo data = agentRpcVoResult.getData();
            authVo.setAgentBindSn(data.getAgentSn());
            authVo.setAgentBindName(data.getAgentName());
            authVo.setAgentBindLockDate(data.getLockDate());
            authVo.setAgentTreePath(data.getAgentTreePath());
            authVo.setDealer(data.getDealer());
            authVo.setDealerId(data.getDealerId());
            authVo.setMaturityTime(data.getMaturityTime());
            authVo.setIsAdsAuth(data.getIsAdsAuth());
            authVo.setAdsLimit(data.getAdsLimit());
            Integer isEnable = data.getIsEnable();
            authVo.setAgentRoleEnable(IsEnableEnum.ENABLE.getValue().equals(isEnable) ? true : false);
            authVo.setAgentId(data.getId());
        }
        return authVo;
    }

    @GetMapping("loadUserByMobile")
    public Result<MemberAuthVo> loadUserByMobile(String mobile) {
        Member member = memberService.selectByMobile(mobile);
        MemberAuthVo authVo = null;
        if (null != member) {
            authVo = new MemberAuthVo();
            BeanUtils.copyProperties(member, authVo);
            long agentRoleBindId = member.getAgentRoleBindId();
            if (0 != agentRoleBindId) {
                Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(agentRoleBindId);
                loadMemberAuthVoData(authVo, agentRpcVoResult);
            }
        }
        return ResultUtil.success(authVo);
    }

    @GetMapping("loadUserByOpenId")
    public Result<MemberAuthVo> loadUserByOpenId(String openId) {
        Member member = memberService.selectByOpenId(openId);
        MemberAuthVo authVo = null;
        if (null != member) {
            authVo = new MemberAuthVo();
            BeanUtils.copyProperties(member, authVo);
            long agentRoleBindId = member.getAgentRoleBindId();
            if (0 != agentRoleBindId) {
                Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(agentRoleBindId);
                loadMemberAuthVoData(authVo, agentRpcVoResult);
            }
        }
        return ResultUtil.success(authVo);
    }

    @GetMapping("loadUserByXcxOpenId")
    public Result<MemberAuthVo> loadUserByXcxOpenId(String openId) {
        Member member = memberService.loadUserByXcxOpenId(openId);
        MemberAuthVo authVo = null;
        if (null != member) {
            authVo = new MemberAuthVo();
            BeanUtils.copyProperties(member, authVo);
            long agentRoleBindId = member.getAgentRoleBindId();
            if (0 != agentRoleBindId) {
                Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(agentRoleBindId);
                loadMemberAuthVoData(authVo, agentRpcVoResult);
            }
        }
        return ResultUtil.success(authVo);
    }


    @GetMapping("selectVoForPreOrder")
    public Result<PreOrderMemberVo> selectVoForPreOrder(String memberId) {
        Member member = memberService.getById(memberId);
        PreOrderMemberVo authVo = new PreOrderMemberVo();
        BeanUtils.copyProperties(member, authVo);
        return ResultUtil.success(authVo);
    }

    @GetMapping("selectByAgentId")
    public Result<MPage<AgentMemberVo>> selectByAgentId(@RequestParam(value = "agentId") long agentId,
                                                        @RequestParam(value = "currentPage") String currentPage,
                                                        @RequestParam(value = "pageSize") String pageSize) {

        MPage<AgentMemberVo> member = memberService.selectAgentMemberOfPage(initMPage(), agentId);
        System.out.println(JSON.toJSONString(member));
        return ResultUtil.success(member);
    }

    /*
     * 更新用户积分，point代表积分数量，
     * inOrOut 代表增加和减少 1代表增加，2代表减少
     * */
    @GetMapping("updatePoint")
    public Result updatePoint(@RequestParam(value = "memberId") Long memberId,
                              @RequestParam(value = "point") Long point,
                              @RequestParam(value = "inOrOut") Integer inOrOut,
                              @RequestParam(value = "desp") String desp,
                              @RequestParam(value = "operator") Long operatorId) {
        //memberService.handlerPoint(memberId, point, inOrOut, desp);
        return ResultUtil.success(memberService.handlerPoint(memberId, point, inOrOut, desp, operatorId));
    }


    /**
     * 方法描述:  创建会员
     * @Author Small
     * @param bindDto
     * @Date 2020/4/28 11:08
     * @return com.weixing.mall.base.wrapper.Result
     */
    @PostMapping("createMember")
    public Result createMember(@RequestBody MemberAgentBindDto bindDto) {
        Member member = new Member();
        member.setMobile(bindDto.getMobile());
        member.setPassword(CommonUtil.encryptPassword(bindDto.getPassword()));
        member.setIsAgent(WhetherEnum.YES.getValue());
        member.setAgentRoleBindId(bindDto.getAgentId());
        return ResultUtil.success();

    }

    /**
     * 积分奖励处理
     * @param memberId  会员ID （必填）
     * @param code  奖励code值（必填）
     * @param amount 若是下单  此参数为下单金额
     * @param operatorId  操作人
     * @return
     */
    @GetMapping("bonusPointsHandle")
    public Result bonusPointsHandle(@RequestParam(value = "memberId") Long memberId,
                                    @RequestParam(value = "code") String code,
                                    @RequestParam(value = "amount") BigDecimal amount,
                                    @RequestParam(value = "operator") Long operatorId) {
        memberService.bonusPointsHandle(memberId, code, amount, operatorId);
        return ResultUtil.success();
    }


    @PostMapping("updateOpenId")
    public Result updateOpenId(String openId, String mobile) {
        Member member = memberService.selectByMobile(mobile);
        if (null != member) {
            member.setOpenid(openId);
        }
        memberService.updateById(member);
        return ResultUtil.success();
    }


    @PostMapping("xcxRegister")
    public Result xcxRegister(String openId, String mobile) {
       memberService.register(openId,mobile);
        return ResultUtil.success();
    }

    @PostMapping("updateXcxOpenId")
    public Result updateXcxOpenId(String openId, String mobile) {
        Member member = memberService.selectByMobile(mobile);
        if (null != member) {
            member.setXcxopenid(openId);
        }
        memberService.updateById(member);
        return ResultUtil.success();
    }

    @PostMapping("removeBindAgent")
    public Result removeBindAgent(String agentId) {
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>();
        wrapper.eq("agent_role_bind_id", agentId);
        Member member = memberService.getOne(wrapper);
        if (null != member) {
//            member.setIsAgent(WhetherEnum.NO.getValue());
//            member.setAgentRoleBindId(0L);

            Result<Integer> result = orderServiceRpc.checkMemberOrderByMemberId(member.getId());
            if (!result.isSuccess()) {
                return ResultUtil.error("查询关联会员订单异常，请稍后重试");
            }
            if (WhetherEnum.YES.getValue().equals(result.getData())) {
                return ResultUtil.error("该会员有订单，不允许删除");
            }
        }
        memberService.removeById(member.getId());
        return ResultUtil.success();
    }

    @PostMapping("resetPwd")
    public Result resetPwd(Long agentId, String newPwd) {
        QueryWrapper<Member> wrapper = new QueryWrapper<Member>();
        wrapper.eq("agent_role_bind_id", agentId);
        Member member = memberService.getOne(wrapper);
        if (null != member) {
            member.setPassword(CommonUtil.encryptPassword(newPwd));
            memberService.updateById(member);
        }
        return ResultUtil.success();
    }


    @GetMapping("loadAgentCid")
    public Result<String> loadAgentCid(Long agentId) {
        return ResultUtil.success().setData(memberService.loadAgentCid(agentId));
    }
}
